<template>
  <div style="width: 100%; height: 100%" class="transfer-user">
    <ElementDialog ref="dialog" embed :visible="visible" title="用户列表" width="930px" height="500px" @open="onOpen">
      <ElRow :span="24" style="height: 100%">
        <ElCol :xs="24" :sm="24" :md="6" class="user__tree" style="height: 100%; overflow: auto">
          <ElTree
            :data="treeData1"
            :props="default_tree_props"
            :expand-on-click-node="false"
            @node-click="handleNodeClick" />
        </ElCol>
        <ElCol :xs="24" :sm="24" :md="18" class="user__main" style="height: 100%">
          <ElTransfer
            v-model="value"
            style="height: 100%"
            filterable
            :titles="titles"
            :props="transfterProp"
            :filter-method="filterMethod"
            filter-placeholder="请输入用户名称"
            :left-default-checked="leftArray"
            :right-default-checked="rightArray"
            :data="data"
            @change="handleChange"
            @right-check-change="rightCheckChange" />
        </ElCol>
      </ElRow>
      <template #footer>
        <ElButton type="primary" @click="transferClick">确定</ElButton>
      </template>
    </ElementDialog>
  </div>
</template>

<script>
  import { fetchList, selectUserList, selectUserVoByRoleId } from '@/api/admin/user'
  import { fetchTree } from '@/api/admin/dept'
  import { saveUserRoleInfo } from '@/api/admin/role'
  import { Transfer } from 'element-ui'

  export default {
    name: 'TransferUser',
    components: {
      ElTransfer: Transfer
    },
    props: {
      visible: Boolean,
      selectType: {
        type: String,
        default: 'default'
      },
      roleId: {
        type: String,
        default: '-1'
      }
    },
    data() {
      return {
        searchForm: {},
        treeData1: [],
        titles: ['未选用户列表', '已选用户列表'],
        default_tree_props: { label: 'name', value: 'id' },
        tableData: [],
        data: [],
        value: [],
        role: '-1',
        transfterProp: {
          label: 'realName',
          key: 'userId',
          disabled: false
        },
        leftArray: [],
        rightArray: [],
        transfterData: []
      }
    },
    watch: {
      roleId() {
        this.role = this.roleId
      }
    },
    created() {
      this.init()
    },
    methods: {
      init() {
        fetchTree().then(response => {
          this.treeData1 = response.data.data
        })
      },
      change(rows) {
        this.rows = rows
      },
      getPage(page, params) {
        // 选择Userinfo表没有的 user信息
        if (this.selectType !== 'default') {
          return selectUserList(
            Object.assign(
              {
                current: page.currentPage,
                size: page.pageSize
              },
              params,
              this.searchForm
            ),
            this.selectType
          )
        } else {
          return fetchList(
            Object.assign(
              {
                current: page.currentPage,
                size: page.pageSize
              },
              params,
              this.searchForm
            )
          )
        }
      },
      handleNodeClick(data) {
        if (this.selectType !== 'default') {
          selectUserList({ current: 1, size: 9999, deptId: data.id }, this.selectType).then(response => {
            this.tableData = response.data.data.records
            this.data = response.data.data.records
          })
        } else {
          fetchList({ current: 1, size: 999, deptId: data.id }).then(response => {
            this.tableData = response.data.data.records
            this.data = response.data.data.records
            if (!this.$isBlank(this.transfterData)) {
              // 拼接所选用户。
              this.transfterData.forEach(row => {
                if (this.$isBlank(this.data)) {
                  this.data.push(row)
                } else {
                  if (this.data.findIndex(item => item.userId === row.userId) === -1) {
                    this.data.push(row)
                  }
                }
              })
            }
          })
        }
      },
      filterMethod(query, item) {
        if (this.$isBlank(item.realName)) {
          return false
        }
        return item.realName.indexOf(query) > -1
      },
      transferClick() {
        if (this.$isBlank(this.transfterData)) {
          this.$message.warning('请选择用户！')
          return
        }
        const saveUserRoleList = []
        this.transfterData.forEach(row => {
          saveUserRoleList.push({
            roleId: this.roleId,
            userId: row.userId
          })
        })
        saveUserRoleInfo(saveUserRoleList).then(response => {
          if (response.data.data) {
            this.$message.success('修改成功！')
            this.$refs.dialog.hide()
          } else {
            this.$message.warning('修改失败！')
          }
        })
      },
      handleChange(value, direction, movedKeys) {
        if (direction === 'right') {
          this.rightArray = value
          value.forEach(val => {
            const index = this.data.findIndex(item => item.userId === val)
            // 保存所选用户
            if (this.transfterData.findIndex(item => item.userId === val) === -1) {
              this.transfterData.push(this.data[index])
            }
          })
        }
        if (direction === 'left') {
          this.transfterData = this.transfterData.filter(user => {
            let result = false
            movedKeys.forEach(leftUser => {
              if (leftUser === user.userId) {
                result = true
              }
            })
            return !result
          })
        }
      },
      rightCheckChange(value, direction, movedKeys) {
        // console.log(value, direction, movedKeys)
      },
      onOpen() {
        selectUserVoByRoleId(this.roleId).then(response => {
          this.rightArray = []
          this.value = []
          this.data = response.data.data
          this.transfterData = this.data

          this.data.forEach(item => {
            this.rightArray.push(item.userId)
            this.value.push(item.userId)
          })
        })
      }
    }
  }
</script>

<style lang="scss">
  .el-transfer-panel {
    position: relative;
    display: inline-block;
    box-sizing: border-box;
    width: 250px;
    height: 500px;
    max-height: 100%;
    overflow: hidden;
    vertical-align: middle;
    background: #fff;
    border: 1px solid #ebeef5;
    border-radius: 4px;
  }

  .el-transfer-panel__body {
    height: 400px;
  }

  .el-transfer-panel__list.is-filterable {
    height: 380px;
    padding-top: 0;
  }
</style>
